package com.ssyx.acl.utils;

import com.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:PermissionHelper
 * Description:
 *
 * @Author kay
 * @Create 2024/4/25 16:44
 * @Version 1.0
 */
//构建菜单
public class PermissionHelper {

    public static List<Permission> build(List<Permission> AllPermissionList){
        //创建最终数据封装集合
        List<Permission> trees = new ArrayList<>();
        //遍历所有菜单集合,得到第一层数据,菜单的第一层在数据库中pid=0
        for(Permission permission : AllPermissionList){
            //菜单的第一层在数据库中pid=0
            if(permission.getPid() == 0){
                permission.setLevel(1);
                //调用方法,从第一层开始往下找
                trees.add(findChildren(permission,AllPermissionList));
            }
        }
        return trees;
    }

    //递归向下查找子菜单
    private static Permission findChildren(Permission permission, List<Permission> allPermissionList) {
        permission.setChildren(new ArrayList<Permission>());
        //遍历allPermissionList所有菜单数据
        //判断,在所有菜单数据中,pid = 当前菜单permission的id,那么这些菜单就是当前菜单permission的子菜单
        for(Permission it : allPermissionList){
            //it 表示allPermissionList中的目标子菜单
            if(it.getPid().longValue() == permission.getId().longValue()){
                //设置子菜单的层级数+1
                it.setLevel(permission.getLevel()+1);
                if (permission.getChildren() == null) {
                    permission.setChildren(new ArrayList<>());
                }
                //封装下一层数据
                permission.getChildren().add(findChildren(it,allPermissionList));
            }
        }
        return permission;
    }
}
